<?php
/**
 * Created by PhpStorm.
 * User: 跳梁
 * Date: 2015/10/29
 * Time: 15:19
 */
class OrderStatisticsAction extends Action{
    public function getVendorList(){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $VendorModel = M("mivendor");
        Session::switchCustomer($customerId);
        $vendorWhere['a.deleted']=array('eq',0);
        $vendorWhere["b.customerId"] = array("eq",$customerId);
        $vendorList = $VendorModel->alias('a')->join("inner join wx_customer_user b on a.fromCustomerUserId=b.id")
            ->field("a.id,b.loginName")
            ->where($vendorWhere)
            ->order("a.updateTime desc")
            ->select();
        $result["vendorList"]=$vendorList;
        Output::instance()->object($result);
    }

    public function getOrderStatistics($startTime=null,$endTime=null,$vid=null,$channelId=null)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $orderModel = M("module_product_order");
        Session::switchCustomer($customerId);
        $where["ord.fromCustomerId"] = array("eq", $customerId);
        $where["ord.type"] = array("eq", 'buy');
        if (isset($startTime) && $startTime) {
            $where['ord.createTime'] = array('gt', $startTime);
        }
        if (isset($endTime) && $endTime) {
            $where['ord.createTime'] = array('lt', $endTime);
        }
        if (isset($endTime) && $endTime && isset($startTime) && $startTime) {
            $where['ord.createTime'] = array(array('gt', $startTime), array('lt', $endTime));
            isset($vid) && $vid ? $where["ord.vId"] = array("eq", $vid) : "";
            isset($channelId) && $channelId ? $where["ord.channelId"] = array("eq", $channelId) : "";
            $where["_string"] = "ord.status <> '" . order_status_refund . "' and ord.status <>'" . ORDER_STATUS_REFUNDING . "' and
                            ord.status<>'" . ORDER_STATUS_PAYING . "' and ord.status <>'" . ORDER_STATUS_CLOSED . "' and
                            ord.status<>'" . ORDER_STATUS_REFUNDEDPART . "' and
                            ord.status<>'" . order_status_notsubmit . "' and ord.status<>'teaming' and (ord.freebuy<>'1' or ord.freebuy is NULL) and
                            (ord.orderType<>'3' or ord.orderType is NULL)";
            $map = $where;
            $orderInfo = $orderModel->alias("ord")
                ->where($where)
                ->field("COUNT(ord.id) AS ordCount,sum(ord.price) as price,AVG(ord.price) as avgPrice,sum(couponMoney) as couponMoney,sum(purseMoney) as purseMoney")
                ->find();
            $cutInfo = $orderModel->alias("ord")
                ->join("inner join wx_module_product_order_detail detail on ord.id=detail.oid")
                ->where($where)
                ->field("sum(detail.isVendorCut) as vendorCut,sum(isMiUserCut) as miUserCut,sum(isRefereeCut) as refereeCut,sum(isParentRefereeCut) as parentRefereeCut,sum(isLordCut) as lordCut")
                ->find();
            $cutInfo['saleCut'] = $cutInfo['miUserCut'] + $cutInfo['refereeCut'] + $cutInfo['parentRefereeCut'] + $cutInfo['lordCut'];
            $cutInfo['profit'] = $orderInfo['price'] - $cutInfo['vendorCut'] - $cutInfo['saleCut'];
            $proCount = $orderModel->alias("ord")
                ->join("inner join wx_module_product_order_detail detail on ord.id=detail.oid")
                ->where($where)
                ->field("sum(detail.count) as proCount")
                ->find();
            $orderInfo['proCount'] = $proCount['proCount'];
            $result = array();
            //组团为成功订单统计
            $where["_string"] = "(ord.status='teaming' or ord.status='" . ORDER_STATUS_REFUNDING . "' or ord.status='" . ORDER_STATUS_REFUNDEDPART . "' or ord.status='" . order_status_refund . "') and ord.isTeam='1' ";
            $teamingInfo = $orderModel->alias("ord")
                ->where($where)
                ->field("count(ord.id) as teamingCount,sum(ord.price) as teamingPrice")
                ->find();
            //团购订单统计
            $where["_string"] = "ord.status <> '" . order_status_refund . "' and ord.status <>'" . ORDER_STATUS_REFUNDING . "' and
                            ord.status<>'" . ORDER_STATUS_PAYING . "' and ord.status <>'" . ORDER_STATUS_CLOSED . "' and
                            ord.status<>'" . ORDER_STATUS_REFUNDEDPART . "' and
                            ord.status<>'" . order_status_notsubmit . "' and ord.status<>'teaming' and ord.isTeam='1'";
            $teamInfo = $orderModel->alias("ord")
                ->join("inner join wx_module_team_order team on ord.teamId=team.id")
                ->where($where)
                ->field("count(ord.id) as teamCount,sum(ord.price) as teamPrice")
                ->find();
            //夺宝订单统计
            $where["_string"] = "ord.orderType='3'";
            $indianaInfo = $orderModel->alias("ord")
                ->where($where)
                ->field("count(ord.id) as indianaCount,sum(ord.price) as indianaPrice")
                ->find();
            //代言订单统计
            $where["_string"] = "ord.freebuy='1'";
            $freeInfo = $orderModel->alias("ord")
                ->where($where)
                ->field("count(ord.id) as freeCount,sum(ord.price) as freePrice")
                ->find();
            //秒杀订单统计
            $where["_string"] = "ord.status <> '" . order_status_refund . "' and ord.status <>'" . ORDER_STATUS_REFUNDING . "' and
                            ord.status<>'" . ORDER_STATUS_PAYING . "' and ord.status <>'" . ORDER_STATUS_CLOSED . "' and
                            ord.status<>'" . ORDER_STATUS_REFUNDEDPART . "' and
                            ord.status<>'" . order_status_notsubmit . "' and ord.isActivity='1'";
            $activityInfo = $orderModel->alias("ord")
                ->where($where)
                ->field("count(ord.id) as activityCount,sum(ord.price) as activityPrice")
                ->find();
            $echarData = $this->orderEchar($map, $startTime, $endTime);
            $result = array_merge($result, $teamingInfo, $orderInfo, $teamInfo, $indianaInfo, $freeInfo, $activityInfo, $cutInfo);
            $result['avgPrice'] = sprintf("%.2f",$result['avgPrice']);
            $result['data'] = $echarData['data'];
            Output::instance()->object($result);
        }
    }
    //密友订单统计
    public function miUserOrder($nickname=null,$startTime=null,$endTime=null,$vid=null,$start=0,$limit=10,$isExport=NULL){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $quanUser =M("quan_user");
        $orderModel = M("module_product_order");
        Session::switchCustomer($customerId);
        $time = '';
        if(isset($startTime)&&$startTime){
            $time .= "and ord.createTime>'".$startTime."'";
        }
        if(isset($endTime)&&$endTime){
            $time.="and ord.createTime<'".$endTime."'";
        }
        isset($vid)&&$vid?$where["ord.vId"]=array("eq",$vid):"";
        $where["_string"]="ord.status <> '".order_status_refund."' and ord.status <>'".ORDER_STATUS_REFUNDING."' and
                            ord.status<>'".ORDER_STATUS_PAYING."' and ord.status <>'".ORDER_STATUS_CLOSED."' and
                            ord.status<>'".order_status_notsubmit."' and ord.status<>'teaming' and (ord.freebuy<>'1' or ord.freebuy is NULL) and
                            (ord.orderType<>'3' or ord.orderType is NULL)".$time;
        $where["ord.fromCustomerId"]=array("eq",$customerId);
        $where["a.deleted"]=array("eq",0);
        $where["a.status"]=array("eq",1);
        $nickname?$where['b.fullName']=array("like","%$nickname%"):"";
        if($isExport){
            $userInfo = $quanUser->alias("a")
                ->join("inner join wx_module_product_order ord on a.qid=ord.qid and a.uid=ord.miUid")
                ->join("inner join wx_".$customerId."_user b on a.uid=b.id")
                ->join("inner join wx_miyouquan c on a.qid = c.id")
                ->field("c.name,b.fullName,b.phone,count(ord.id) as orderCount,sum(ord.price) as orderPrice")
                ->where($where)
                ->group("a.qid,a.uid")
                ->order("orderCount DESC")
                ->select();
            $data[0] = array(
                'name'=>"密友圈",
                'fullName'=>'注册姓名',
                'phone'=>'手机号',
                'orderCount'=>'订单数',
                'orderPrice'=>'销售额',
                'isNum'=>'3,4',
                'istitle'=>'1'
            );
            foreach ($userInfo as $k1 => $v1) {
                $data[] = $v1;
            }
            Output::instance()->objArrayExcel('订单统计'.date("Y-m-d H:i:s"), '', $data);
        }else{
            $userInfo = $quanUser->alias("a")
                ->join("inner join wx_module_product_order ord on a.qid=ord.qid and a.uid=ord.miUid")
                ->join("inner join wx_".$customerId."_user b on a.uid=b.id")
                ->join("inner join wx_miyouquan c on a.qid = c.id")
                ->field("c.name,c.logo,a.headimgurl,b.fullName,b.phone,count(ord.id) as orderCount,sum(ord.price) as orderPrice")
                ->where($where)
                ->group("a.qid,a.uid")
                ->order("orderCount DESC")
                ->limit($start,$limit)
                ->select();
            if($userInfo){
                $count =  $quanUser->alias("a")
                    ->join("inner join wx_module_product_order ord on a.qid=ord.qid and a.uid=ord.miUid")
                    ->join("inner join wx_".$customerId."_user b on a.uid=b.id")
                    ->join("inner join wx_miyouquan c on a.qid = c.id")
                    ->field("c.name,c.logo,a.headimgurl,b.fullName,b.phone,count(ord.id) as orderCount,sum(ord.price) as orderPrice")
                    ->where($where)
                    ->group("a.qid,a.uid")
                    ->order("orderCount DESC")
                    ->select();
                $count=count($count);
                Output::instance()->objArray($userInfo,$count);
            }else{
                Output::instance()->resultCode(code_success);
            }
        }
    }


    /**
     * 订单图形化统计数据
     * @param $where            筛选条件
     * @param $startTime        开始时间
     * @param $endTime          结束时间
     * @return mixed            返回
     */
    public function orderEchar($where, $startTime, $endTime)
    {
        //实例化数据库模型
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $orderModel = M("module_product_order");
        Session::switchCustomer($customerId);
        //查询相差天数
        $dateNum = $this->diffDate($startTime, $endTime);
        for ($i = 0; $i <= $dateNum['day']; $i++) {
            if ($i == 0) {
                $startTime = date("Y-m-d", strtotime("+" . $i . " day", strtotime($startTime)));
                $endTime = date("Y-m-d", strtotime("+1 day", strtotime($startTime)));
            } else {
                $startTime = date("Y-m-d", strtotime("+1 day", strtotime($startTime)));
                $endTime = date("Y-m-d", strtotime("+1 day", strtotime($startTime)));
            }

            $where['ord.createTime'] = array(array('gt', $startTime), array('lt', $endTime));
            $orderInfo = $orderModel->alias("ord")
                ->where($where)
                ->field("COUNT(ord.id) AS ordCount,ifnull(SUM(price),0) as price ")
                ->find();
            $res['data']['series'][0]['name'] = '订单数';
            $res['data']['series'][0]['data'][$i]['ordCount'] = $orderInfo['ordCount'];
            $res['data']['series'][0]['data'][$i]['date'] = $startTime;
            $res['data']['series'][1]['name'] = '订单金额';
            $res['data']['series'][1]['data'][$i]['price'] = $orderInfo['price'];;
            $res['data']['series'][1]['data'][$i]['date'] = $startTime;
        }
        return $res;
    }

    /*
        *function：计算两个日期相隔多少年，多少月，多少天
        *param string $date1[格式如：2011-11-5]
        *param string $date2[格式如：2012-12-01]
        *return array array('年','月','日');
        */
    public function diffDate($begin_time, $end_time)
    {
        $begin_time = strtotime($begin_time);
        $end_time = strtotime($end_time);
        if ($begin_time < $end_time) {
            $starttime = $begin_time;
            $endtime = $end_time;
        } else {
            $starttime = $end_time;
            $endtime = $begin_time;
        }
        $timediff = $endtime - $starttime;
        $days = intval($timediff / 86400);
        $remain = $timediff % 86400;
        $hours = intval($remain / 3600);
        $remain = $remain % 3600;
        $mins = intval($remain / 60);
        $secs = $remain % 60;
        $date1 = explode('-',$begin_time);
        $date2 = explode('-',$end_time);
        $moth = abs($date1[0] - $date2[0]) * 12 + abs($date1[1] - $date2[1]);
        $res = array("day" => $days, "hour" => $hours, "min" => $mins, "sec" => $secs);
        return $res;
    }

}